package com.hzsai.socket;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.UUID;

/**
 * hzsai 2019/11/6
 * usage:
 **/

@Component
public class SocketIOEventHandler {

    private static final Logger logger = LoggerFactory.getLogger(SocketIOEventHandler.class);

    @Autowired
    private SocketIOServer socketIOServer;

    public SocketIOEventHandler() {

    }

    /**
     * 客户端UUID
     */
//    static private ArrayList<UUID> clientList = new ArrayList();
    static private HashSet<UUID> clientList = new HashSet<>();

    /**
     * 客户端连接时
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {

        logger.debug("Client: " + client.getSessionId() + " connected.");
        System.out.println(socketIOServer.getClient(client.getSessionId()));

        clientList.add(client.getSessionId());
        logger.debug("Current Client size:  " + clientList.size());
    }

    /**
     * 客户端断开时
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {

        clientList.remove(client.getSessionId());

        logger.debug("Client: " + client.getSessionId() + " disconnected.");
        logger.debug("Client size:  " + clientList.size());
    }

    /**
     * 直接发送消息给全部客户端
     * @param event
     * @param msg
     */
    public void sendMsg(String event, String msg) {
        for (UUID id : clientList) {
            if (socketIOServer.getClient(id) == null)
                continue;
            socketIOServer.getClient(id).sendEvent(event, msg);
        }
    }

    @OnEvent("dodo-bird-qiu-qiu")
    public void demoEvent(SocketIOClient client, AckRequest ack, Object data) {
        System.out.println(client.getHandshakeData());
        ack.sendAckData("dodo");
    }

    /**
     * 接受消息样例
     * @param client
     * @param ackRequest
     * @param data
     */
    @OnEvent(value = "chatevent")
    public void onEvent(SocketIOClient client, AckRequest ackRequest, Object data) {
        logger.info("接收到客户端消息: {}", data.toString());
        if (ackRequest.isAckRequested()) {
            // send ack response with data to client
            ackRequest.sendAckData("服务器回答Socket.EVENT_MESSAGE", "好的");
            logger.info("HaHaHaHa~");
        }
    }
}
